package main

import (
	"io/ioutil"
	"log"
	"net/http"

	"github.com/gorilla/websocket"
)

var upgrader = websocket.Upgrader{
	ReadBufferSize:  1024,
	WriteBufferSize: 1024,
}

var clients = make(map[*websocket.Conn]bool)
var broadcast = make(chan []byte)

func handleWebSocket(w http.ResponseWriter, r *http.Request) {
	upgrader.CheckOrigin = func(r *http.Request) bool { return true }
	ws, err := upgrader.Upgrade(w, r, nil)
	if err != nil {
		log.Fatal(err)
	}
	defer ws.Close()

	clients[ws] = true

	for {
		_, msg, err := ws.ReadMessage()
		if err != nil {
			log.Println("WebSocket读取数据失败:", err)
			delete(clients, ws)
			break
		}
		broadcast <- msg
	}
}

func handleTCPData(w http.ResponseWriter, r *http.Request) {
	if r.Method != "POST" {
		http.Error(w, "仅支持POST方法", http.StatusMethodNotAllowed)
		return
	}

	data, err := ioutil.ReadAll(r.Body)
	if err != nil {
		http.Error(w, "读取请求体失败", http.StatusInternalServerError)
		return
	}

	broadcast <- data
	w.WriteHeader(http.StatusOK)
}

func main() {
	http.HandleFunc("/ws", handleWebSocket)
	http.HandleFunc("/tcpdata", handleTCPData)

	go func() {
		for {
			msg := <-broadcast
			for client := range clients {
				err := client.WriteMessage(websocket.TextMessage, msg)
				if err != nil {
					log.Printf("WebSocket发送数据失败: %v", err)
					client.Close()
					delete(clients, client)
				}
			}
		}
	}()

	log.Println("WebSocket服务器启动，监听 8080 端口...")
	log.Fatal(http.ListenAndServe("localhost:8080", nil))
}
